package com.filetransfer.controller;

import com.filetransfer.model.dto.DeviceDTO;
import com.filetransfer.model.vo.ApiResult;
import com.filetransfer.service.DeviceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 设备控制器
 */
@Slf4j
@RestController
@RequestMapping("/device")
@RequiredArgsConstructor
public class DeviceController {

    private final DeviceService deviceService;
    
    /**
     * 获取在线设备列表
     */
    @GetMapping("/list")
    public ApiResult<List<DeviceDTO>> list() {
        return ApiResult.success(deviceService.getOnlineDevices());
    }
    
    /**
     * 发现设备
     */
    @PostMapping("/discover")
    public ApiResult<Integer> discover() {
        int count = deviceService.discoverDevices();
        return ApiResult.success(count);
    }
    
    /**
     * 注册设备
     */
    @PostMapping("/register")
    public ApiResult<String> register(@RequestBody DeviceDTO deviceDTO, HttpServletRequest request) {
        // 设置设备IP地址（如果请求中没有提供）
        if (deviceDTO.getIpAddress() == null || deviceDTO.getIpAddress().isEmpty()) {
            deviceDTO.setIpAddress(getClientIp(request));
        }
        
        String deviceId = deviceService.registerDevice(deviceDTO);
        return ApiResult.success(deviceId);
    }
    
    /**
     * 更新设备状态
     */
    @PutMapping("/status")
    public ApiResult<Boolean> updateStatus(@RequestParam String deviceId, @RequestParam Integer status) {
        boolean result = deviceService.updateDeviceStatus(deviceId, status);
        return ApiResult.success(result);
    }
    
    /**
     * 更新设备名称
     */
    @PostMapping("/rename")
    public ApiResult<Boolean> rename(@RequestBody DeviceDTO deviceDTO) {
        boolean result = deviceService.updateDeviceName(deviceDTO.getId(), deviceDTO.getDeviceName());
        return ApiResult.success(result);
    }
    
    /**
     * 获取设备详情
     */
    @GetMapping("/{deviceId}")
    public ApiResult<DeviceDTO> getDeviceDetail(@PathVariable String deviceId) {
        DeviceDTO deviceDTO = deviceService.getDeviceDetail(deviceId);
        if (deviceDTO != null) {
            return ApiResult.success(deviceDTO);
        } else {
            return ApiResult.error("设备不存在");
        }
    }
    
    /**
     * 获取客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        
        // 如果是多级代理，获取第一个IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        
        return ip;
    }
} 